package pc;

// 线程之前通信
// 生产者消费者
// 判断等待，执行业务，通知

//A 和 B 之间通信
// A++ 完后 通知 B--
public class PC {

    public static void main(String[] args) {

        ZY zy = new ZY();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                try {
                    zy.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                try {
                    zy.unincr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                try {
                    zy.unincr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                try {
                    zy.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"D").start();
    }


   static class ZY{
        private int num = 0;


        public synchronized void incr() throws InterruptedException {
            while(num != 0){
                //等待
                this.wait();
            }
            num++;
            System.out.println("num ++ 当前num值:"+num);
            //唤醒其他线程
            this.notifyAll();
        }


        public synchronized void unincr() throws InterruptedException {
            while(num == 0){
                //等待
                this.wait();
            }
            num--;
            System.out.println("num -- 当前num值:"+num);
            this.notifyAll();
        }
    }
}
